package moduleutil

import (
	"sync"

	"gitee.com/tomatomeatman/golang-repository/bricks3/function/configutil"
	"gitee.com/tomatomeatman/golang-repository/bricks3/function/reflectutil"
	"gitee.com/tomatomeatman/golang-repository/bricks3/model/globalvariable"
	"github.com/gin-gonic/gin"
)

var (
	mainDb     string    //主库名
	mainDbOnce sync.Once //单次赋值操作
)

// 获取主库名
func GetMainDb() string {
	mainDbOnce.Do(func() {
		mainDb = configutil.ReadConfigKey("", "DataSource", "MainDb", "").(string)
	})

	return mainDb
}

func CurrentLoginUserId(ctx *gin.Context) string {
	ctx.Request.ParseForm() //警告:必须先 解析所有请求数据

	form := ctx.Request.Form
	if form == nil {
		return ""
	}

	return form.Get("loginUserId")
}

// 按模块调用方法
func DoMethod(moduleName string, methodName string, params ...interface{}) (bool, string, interface{}) {
	module := globalvariable.Get("Module@" + moduleName)

	if module == nil {
		module = globalvariable.Get("Module@VirtualService")
	}

	if module == nil {
		return false, "模块不存在", 1001
	}

	resultValue := reflectutil.DoMethod(module, methodName, params...)
	if len(resultValue) < 3 {
		return false, "返回结果与预期不符", 1002
	}

	return resultValue[0].Interface().(bool), resultValue[1].Interface().(string), resultValue[2].Interface()
}
